angular.module('activities.services', [])

.factory("RHTTP", (Config, $state, $rootScope, Toast) ->
  rhttp = {}

  checkConn = ->
    # return unless activity_sidao.utils.isDevice()
    networkState = navigator.connection.type

    states = {}
    states[Connection.UNKNOWN]  = '未知类型连接';
    states[Connection.ETHERNET] = '以太网';
    states[Connection.WIFI]     = 'WiFi';
    states[Connection.CELL_2G]  = '2G';
    states[Connection.CELL_3G]  = '3G';
    states[Connection.CELL_4G]  = '4G';
    states[Connection.CELL]     = '蜂窝数据连接';
    states[Connection.NONE]     = '无连接';

    console.log('Connection type: ' + states[networkState]);
    Toast.show('Connection type: ' + states[networkState]);

    if Connection.NONE == networkState || Connection.UNKNOWN == networkState
      $rootScope.$emit "networkconn:none"
      Toast.show "无网络连接，请检查手机设置"

    if Connection.CELL == networkState ||
       Connection.CELL_2G == networkState ||
       Connection.CELL_3G == networkState ||
       Connection.CELL_4G == networkState
      $rootScope.$emit "networkconn:cell"

  rhttp.p = (url, data, config={})->
    data = data or {}
    data.client_version = Config.version
    # data.market_vendor = Config.market_vendor
    data.session_id = window.localStorage["rt_session_id"]
    data.session_id = activity_sidao.storage.account().session_id unless data.session_id?
    # data.device = ionic.Platform.platform()
    data.jpush_token = activity_sidao.storage.deviceInfo().jpush_token
    data.ios_token = activity_sidao.storage.deviceInfo().ios_token

    $rootScope.load_status = null
    $rootScope.loading = true

    console.debug "api: #{url} post data is: "
    console.debug data


    $.post(url, data).done( (ret) ->
      $rootScope.load_status = 1
      # do something
      $rootScope.loading = false
      console.debug "api: #{url} get data is: "
      console.debug ret
    ).fail( (err) ->
      $rootScope.load_status = 0
      $rootScope.loading = false
      console.log  "#{err.status}: #{err.responseText}"

      switch err.status
        when 0
          # checkConn()
          $rootScope.$emit "loading:hide"

        when 404 # 地址不存在
          Toast.show '访问地址不存在'
          $rootScope.$emit "loading:hide"
          throw "stop post chain"

        when 503 # 通用提示错误
          try
            ret = JSON.parse(err.responseText)
            Toast.show ret.status.msg
          catch
            Toast.show '网络不稳定，请稍后重试'

          $rootScope.$emit "loading:hide"
          throw "stop post chain"

        when 502 # 自定义错误，由具体 API 处理
          console.debug  "#{err.responseText}"

        when 500 # 系统错误
          try
            ret = JSON.parse(err.responseText)
            Toast.show ret.status.msg
          catch
            console.log "解析json失败"

        when 501 # 系统定义错误
          try
            ret = JSON.parse(err.responseText)
            switch ret.data.error_type
              when 1 # session 过期，或者需要登陆
                activity_sidao.storage.deleteAccount()
              when 2 # 有新版本，需要强制升级
                cfg = ret.data.detail
                activity_sidao.utils.upgradeApp(cfg, $ionicPopup)
              else
                Toast.show "未知错误类型: #{ret.data.error_type}, 错误信息 #{ret.status.msg}"
                break
          catch err2
            console.log "解析json失败:#{err2}"
            Toast.show '网络不给力哦'
        else # 其他状态码错误
          console.log "尚未定义的错误状态：#{err.status}"
    )
    .complete( (e)->
      $rootScope.$digest() unless $rootScope.$$phase
    )
    .always ()->
      $rootScope.loading = false

  rhttp.h = (url, data, config = {})->
    remote_server_version = config.version || Config.remote_server_default_version
    url = [Config.remote_server, remote_server_version, url].join('/')
    rhttp.p(url, data, config)

  return rhttp
)


.factory('RemoteSrv', (RHTTP,Config) ->
  {
    getSpreadInfo: () ->
      RHTTP.h "/account/spread/info"

    playActivity: (cname)->
      RHTTP.h "/activities/play", {cname: cname}

    getActivityInfo: (cname)->
      RHTTP.h "/activities/info", {cname: cname}

    getPresentRecords: (activity_cname)->
      RHTTP.h "/activities/present_records", {activity_cname: activity_cname}

    getActivityRecords: (cname)->
      RHTTP.h "/activities/activity_records", {cname: cname}

    shareSuccess: (promotion_code, cname)->
      RHTTP.h "/activities/share_success", {promotion_code: promotion_code, cname}

    getAccountInfo: (params) ->
      RHTTP.h "/account/info", params

    givePresent: (cname, activity_cname, present_cname)->
      RHTTP.h "/activities/give_present", {cname: cname, activity_cname: activity_cname, present_cname: present_cname}

    checkPresent: (cname1, cname2)->
      RHTTP.h "/activities/check_present_record", {cname1: cname1, cname2: cname2}

    getAllPresentRecords: ()->
      RHTTP.h "/activities/all_present_records"

    signup: (account) ->
      RHTTP.h "/signup", account

    getValidationCode: (phone, reason) ->
      RHTTP.h "/vcodes", {phone: phone, usage: reason}

    getAddressCode: (address) ->
      RHTTP.h "/addresses/init", address
  }
)
